<?php
namespace App\Logic\SalesReport;
use App\Models\SalesReport\PaymentArea as TPaymentArea;
use App\Models\SalesReport\PaymentClassify as TPaymentClassify;
use App\Models\SalesReport\PaymentDetail as TPaymentDetail;
use App\Models\SalesReport\PaymentTNSummary as TPaymentTNSummary;
use Illuminate\Support\Facades\DB;
class PaymentArea
{
    public static function exePayment($date){
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        try{
            $start = time();
            $start_memory = memory_get_usage();
            DB::beginTransaction();
            $headers = TPaymentTNSummary::headersField();
            $groupByArr = ['area_id'];
            $pc = TPaymentDetail::query()
                ->where('report_date',$date)
                ->selectRaw(TPaymentDetail::_getFields($headers,$groupByArr))
                ->groupBy($groupByArr)
                ->get();
            $rate = [];
            foreach ($pc as $pd){
                $key = $date.'_'.$pd->area_id;
                if(!array_key_exists($key,$rate)){
                    $rate[$key] = TPaymentDetail::getSummaryRateOdds($date,$pd->area_id);
                }
                $rateOdds = $rate[$key];
                $data = TPaymentClassify::_getData($pd,['rate_odds' => $rateOdds]);
                TPaymentArea::query()->updateOrCreate(
                    [
                        'report_date' => $date,
                        'area_id' => $pd->area_id
                    ], $data
                );
            }
            DB::commit();
            $end = time();
            $end_memory = memory_get_usage();
            print_r(($end - $start).'--------'.(($end_memory - $start_memory)/1024/1024));
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }
}
